package condominio.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import com.mysql.jdbc.Connection;

import condominio.excepcion.DAOExcepcion;
import condominio.excepcion.LoginExcepcion;
import condominio.modelo.Persona;
import condominio.util.ConexionBD;

public class PersonaDAO extends BaseDAO {

	public Collection<Persona> listarVigilantes() throws DAOExcepcion {
		System.out.println("PersonaDAO: listarVigilantes()");
		Collection<Persona> c = new ArrayList<Persona>();
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = (Connection) ConexionBD.obtenerConexion();
			String query = "Select apepat, apemat, nombres, dni, email, telefono, direccion from persona where idtipo = 3";
			stmt = con.prepareStatement(query);
			// executeQuery()para Selects
			rs = stmt.executeQuery();
			while (rs.next()) {
				Persona pe = new Persona();

				pe.setApePat(rs.getString("apepat"));
				pe.setApeMat(rs.getString("apemat"));
				pe.setDni(rs.getString("dni"));
				pe.setEmail(rs.getString("email"));
				pe.setTelefono(rs.getString("telefono"));
				pe.setDireccion(rs.getString("direccion"));
				c.add(pe);
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return c;
	}

	public Persona validarLogin(String idUsuario, String clave)	throws DAOExcepcion, LoginExcepcion {
		
		String query = "select usuario, nombres "
				+ "from persona where usuario=? and clave=?";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		Persona vo = new Persona();
		try {
			con = (Connection) ConexionBD.obtenerConexion();			
			stmt = con.prepareStatement(query);
			stmt.setString(1, idUsuario);
			stmt.setString(2, clave);
			rs = stmt.executeQuery();

			if (rs.next()) {
				vo.setUsuario(rs.getString("usuario"));
				vo.setCalve(rs.getString("nombres"));
			} else {
				throw new LoginExcepcion("No existe");
			}
		} catch (LoginExcepcion e) {
			System.err.println(e.getMessage());
			throw new LoginExcepcion(e.getMessage());
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}

}
